<?php
/**
 * 采购单控制器
 */

namespace app\api\controller;

use app\api\exception\ApiServiceException;
use app\api\service\SendService;
use app\common\model\Brand;
use app\common\model\OfferDetail;
use app\common\model\Send;
use app\common\model\Spec;
use app\common\model\Type;
use app\common\validate\SendValidate;
use hg\apidoc\annotation as Apidoc;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Request;
use think\response\Json;

/**
 * @Apidoc\Title("送货单")
 * @Apidoc\Group("index")
 */
class SendController extends ApiBaseController {
	protected array $loginExcept = [
		'api/send/info',
	];

	/**
	 * @Apidoc\Title("列表")
	 * @Apidoc\Desc("列表")
	 * @Apidoc\Method("GET")
	 * @Apidoc\Url("/api/send/index")
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function index(SendService $service): Json {
		try {
			$this->param['user_id'] = $this->uid;
			$data = $service->getList($this->param, $this->page, $this->limit);
			$result = [
				'send' => $data,
			];

			return api_success($result);
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 添加
	 * @param SendValidate $validate
	 * @param SendService $service
	 * @return Json
	 */
	public function add(SendValidate $validate, SendService $service): Json {
		$check = $validate->scene('api_add')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		$result = $service->createData($this->param);

		return $result ? api_success() : api_error();
	}

	/**
	 * @Apidoc\Title("详情")
	 * @Apidoc\Desc("详情")
	 * @Apidoc\Method("GET")
	 * @Apidoc\Url("/api/send/info")
	 * @Apidoc\Query("id",          type="int",require=true, desc="id")
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function info(SendValidate $validate, SendService $service): Json {

		try {

			$result = $service->getDataInfo($this->id);
			return api_success([
				'send' => $result,
			]);

		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	public function edit(SendService $service, SendValidate $validate): Json {
		$this->param['detail'] = json_decode($this->param['detail'], true);
		$detail = $this->param['detail'];
		foreach ($detail as $key => $value) {
			$detail[$key]['money'] = round($value['num'] * $value['price'], 2);
		}
		$this->param['detail'] = $detail;

		$this->param['money'] = array_sum(array_column($this->param['detail'], 'money'));

		try {
			$service->updateData($this->id, $this->param);
			$this->offer_detail($this->id);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}
	public function offer_detail($id) {
		$data = Send::find($id);
		$send = Send::where('school_id', $data['school_id'])->where('send_time', strtotime($data['send_time']))->select()->toArray();
		$detail = array_column($send, 'detail');
		$twoDimArray = [];

		// 遍历三维数组，将其转换为二维数组
		foreach ($detail as $subArray) {
			foreach ($subArray as $item) {
				$twoDimArray[] = $item;
			}
		}
		$detail = $this->array_dos($twoDimArray);

		$offer_detail = OfferDetail::where('id', $data['offer_detail_id'])->findOrEmpty();
		if (!$offer_detail->isEmpty()) {

			$detail = $this->array_do5($detail, $offer_detail['detail']);

			foreach ($detail as $dk => $dv) {
				$detail[$dk]['money'] = round($dv['price'] * $dv['num'], 2);
			}

			$offer_money = array_sum(array_column($detail, 'money'));

			if (!empty($detail)) {
				$offer_detail->save(['detail' => $detail, 'money' => $offer_money]);
			} else {
				$offer_detail->delete();
			}

		}
	}
	/**
	 * 删除
	 * @param SendService $service
	 * @param SendValidate $validate
	 * @return Json
	 */
	public function del(SendService $service, SendValidate $validate): Json {
		$check = $validate->scene('api_del')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {
			$service->deleteData($this->id);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}
	public function export(Request $request, Send $model): void {
		$param = $request->param();
		$param['user_id'] = $this->uid;
		$data = $model->with(['school', 'user'])->scope('where', $param)->select();

		$header = ['学校', '供应商', '采购单号', '配送时间', '总收货金额', '分类', '商品', '规格', '单位', '采购数量', '采购价格', '已收数量', '未收数量', '收货均价', '收货金额', '备注'];

		$body = [];
		foreach ($data as $item) {

			foreach ($item->detail as $key => $value) {
				$record = [];
				$type = Type::where('id', $value['type_id'])->find();
				$record['school'] = $item->school->name ?? '';
				$record['user'] = $item->user->nickname ?? '';
				$record['code'] = $item->code . ' ';
				$record['send_time'] = $item->send_time ?? '';
				$record['all_money'] = $item->money;
				$record['parent'] = Type::where('id', $type['parent_id'])->value('name') ?? '';
				$record['type'] = $type['name'] ?? '';
				$record['spec'] = Spec::where('id', $value['spec_id'])->value('name') ?? '';
				$record['brand'] = Brand::where('id', $value['brand_id'])->value('name') ?? '';
				$record['num'] = $value['num'] ?? '';
				$record['price'] = $value['price'] ?? '';
				$record['shou_num'] = $value['shou_num'] ?? '';
				$record['wei_num'] = $value['wei_num'] ?? '';
				$record['avg_price'] = $value['avg_price'] ?? '';
				$record['money'] = $value['money'] ?? '';
				$record['beizhu'] = $value['beizhu'] ?? '';
				$body[] = $record;
			}

		}

		$this->exportData($header, $body, '采购单数据-' . date('YmdHis'));
	}
	protected function exportData(array $head, array $body, string $name = '', string $title = 'Sheet1'): void {
		try {
			if (empty($name)) {
				$name = date('Y-m-d-H-i-s');
			}

			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->setActiveSheetIndex(0);
			$char_index = range('A', 'Z');

			// 处理超过26列
			$a = 'A';
			foreach ($char_index as $item) {
				$char_index[] = $a . $item;
			}

			// Excel 表格头
			foreach ($head as $key => $val) {
				$sheet->setCellValue($char_index[$key] . '1', $val);
			}

			// Excel body 部分
			foreach ($body as $key => $val) {
				$row = $key + 2;
				$col = 0;
				foreach ($val as $v) {
					$sheet->setCellValue($char_index[$col] . $row, $v);
					$col++;
				}
			}

			$spreadsheet->getActiveSheet()->setTitle($title);

			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
			header('Cache-Control: max-age=0');

			$objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
			$objWriter->save('php://output');
			exit();
		} catch (Exception $e) {
			exit($e->getMessage() . '(' . $e->getFile() . '-' . $e->getLine() . ')');
		}
	}
	// public function export(Request $request, Send $model): void {
	// 	$param = $request->param();
	// 	$data = $model->with(['school', 'user'])->where('id', $param['id'])->find();

	// 	$head = ['商品名称', '单位', '待采购量', '采购价格', '备注', '商品状态', '客户下单明细', '商品条码', '商品编码'];
	// 	$status = [
	// 		'0' => '待采购',
	// 		'1' => '已采购',
	// 		'2' => '待送货',
	// 		'3' => '已送货',
	// 	];
	// 	$body = [];
	// 	foreach ($data['detail'] as $item) {
	// 		$type = Type::where('id', $item['type_id'])->find();
	// 		$spec = Spec::where('id', $item['spec_id'])->find();
	// 		$brand = Brand::where('id', $item['brand_id'])->find();
	// 		$record = [];
	// 		$record['name'] = $type['name'];
	// 		$record['brand'] = $brand['name'];
	// 		$record['num'] = $item['num'];
	// 		$record['price'] = $item['price'];
	// 		$record['beizhu'] = ' ';
	// 		$record['status'] = $status[$item['status'] ?? 0];
	// 		$record['mx'] = '';
	// 		$record['tm'] = '';
	// 		$record['bm'] = '';

	// 		$body[] = $record;
	// 	}
	// 	try {
	// 		$spreadsheet = new Spreadsheet();
	// 		$sheet = $spreadsheet->setActiveSheetIndex(0);

	// 		$sheet->mergeCells("A1:H1"); //合并单元格
	// 		$sheet->mergeCells("B2:C2"); //合并单元格
	// 		$sheet->mergeCells("E2:F2"); //合并单元格
	// 		$sheet->mergeCells("B3:C3"); //合并单元格
	// 		$sheet->mergeCells("E3:F3"); //合并单元格
	// 		$sheet->setCellValue("A1", "送货单(" . $data->user->nickname . ")")->getStyle('A1')->getFont()->setBold(true);
	// 		$sheet->setCellValue("A2", "单据编号")->getStyle('A2')->getFont()->setBold(true);
	// 		$sheet->setCellValue("B2", $data->code . ' ')->getStyle('B2')->getFont()->setBold(true);
	// 		$sheet->setCellValue("D2", "发货日期")->getStyle('D2')->getFont()->setBold(true);
	// 		$sheet->setCellValue("E2", $data->send_time)->getStyle('E2')->getFont()->setBold(true);
	// 		$sheet->setCellValue("G2", "单据金额")->getStyle('G2')->getFont()->setBold(true);
	// 		$sheet->setCellValue("H2", $data->money)->getStyle('H2')->getFont()->setBold(true);
	// 		$sheet->setCellValue("A3", "创建时间")->getStyle('A3')->getFont()->setBold(true);
	// 		$sheet->setCellValue("B3", $data->create_time)->getStyle('B3')->getFont()->setBold(true);
	// 		$sheet->setCellValue("D3", "单据备注")->getStyle('D3')->getFont()->setBold(true);
	// 		$sheet->setCellValue("G3", "单据状态")->getStyle('G3')->getFont()->setBold(true);
	// 		$sheet->setCellValue("H3", $data->status_text)->getStyle('H3')->getFont()->setBold(true);
	// 		$sheet->setCellValue("A4", "学校")->getStyle('A4')->getFont()->setBold(true);
	// 		$sheet->setCellValue("B4", $data->school->name)->getStyle('B4')->getFont()->setBold(true);
	// 		$char_index = range('A', 'Z');
	// 		$name = '采购单数据-' . date('YmdHis');
	// 		// 处理超过26列
	// 		$a = 'A';
	// 		foreach ($char_index as $item) {
	// 			$char_index[] = $a . $item;
	// 		}

	// 		// Excel 表格头
	// 		foreach ($head as $key => $val) {
	// 			$sheet->setCellValue($char_index[$key] . '5', $val);
	// 		}

	// 		// Excel body 部分
	// 		foreach ($body as $key => $val) {
	// 			$row = $key + 6;
	// 			$col = 0;
	// 			foreach ($val as $v) {
	// 				$sheet->setCellValue($char_index[$col] . $row, $v);
	// 				$col++;
	// 			}
	// 		}

	// 		$spreadsheet->getActiveSheet()->setTitle('采购单');

	// 		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	// 		header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
	// 		header('Cache-Control: max-age=0');

	// 		$objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
	// 		$objWriter->save('php://output');
	// 		exit();
	// 	} catch (Exception $e) {
	// 		exit($e->getMessage() . '(' . $e->getFile() . '-' . $e->getLine() . ')');
	// 	}
	// }
	public function array_do5($array1, $array2) {
		//$result = [];
		foreach ($array1 as &$item1) {
			foreach ($array2 as $item2) {
				if ($item1['type_id'] == $item2['type_id']) {
					$item1['price'] = $item2['price']; // 更新price
					//$result[] = $item1;
				}
			}
		}

		//unset($item1);
		return $array1;
	}
	public function array_dos($array) {
		$result = [];

		foreach ($array as $item) {
			$type_id = $item['type_id'];
			if (!isset($result[$type_id])) {
				$result[$type_id] = $item;
			} else {
				$result[$type_id]['num'] += $item['num'];
			}
		}

		$result = array_values($result);
		return $result;
	}
}
